<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :showBefore='true'>
        <span slot="before">共{{page.total}}条记录</span>
        <template v-slot:after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置分页表格 -->

      <el-card>
        <el-table border :data="list">
          <el-table-column align='center' label="序号" sortable="" type="index" width="60px" />
          <el-table-column align='center' label="姓名" sortable="" prop="username" />
          <el-table-column align='center' label="头像" sortable="">
            <template slot-scope="{row}">
              <!-- <img :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                v-imageerror="require('@/assets/common/bigUserHeader.png')" /> -->
              <img slot="reference" v-imagerror="require('@/assets/common/bigUserHeader.png')" :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" alt=""
                @click="showQrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column align='center' label="工号" sortable="" prop="workNumber" />
          <el-table-column align='center' label="聘用形式" sortable="" prop="formOfEmployment"
            :formatter='formatEmployment' />
          <el-table-column align='center' label="部门" sortable="" prop="departmentName" />
          <el-table-column align='center' label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="obj">
              {{obj.row.timeOfEntry|formatDate}}
            </template>
          </el-table-column>
          <el-table-column align='center' label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{row}">
              <el-switch v-model="row.enableState==1" active-color="#13ce66" inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column align='center' label="操作" sortable="" fixed="right" width="280">
            <template v-slot='{row}'>
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 放置分页 -->
        <el-row type="flex" justify="center" style="height:60px" align="middle">
          <el-pagination layout="prev, pager, next" :total="page.total" :current-page='page.page' :page-size='page.size'
            @current-change='changePage'>
          </el-pagination>
        </el-row>
        <!-- //放置分页 -->
      </el-card>
      <!-- //放置分页表格 -->
    </div>
    <!-- 新增员工弹层组件 -->
    <AddEmployee :showDialog.sync="showDialog" />

    <!-- 二维码弹层 -->
    <el-dialog :visible.sync='showCodeDialog' title="二维码">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>

    <!-- 放置员工分配角色组件-->
    <assign-role :showDialog.sync='showRoleDialog' ref="assignRole" :userId='userId' />
    <!-- //放置员工分配角色组件-->
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from '@/views/employees/components/add-employee.vue'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
import QrCode from 'qrcode'
export default {
  components: { AddEmployee, AssignRole },
  data () {
    return {
      //表格数据
      list: [],
      //分页参数
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0 // 总数
      },
      showDialog: false,
      //二维码弹层
      showCodeDialog: false,
      //员工角色分配弹层
      showRoleDialog: false,
      //当前员工id
      userId: null
    }
  },
  watch: {
  },
  created () {
    //获取列表数据
    this.getEmployeeList()
  },
  mounted () {
  },
  methods: {
    //获取列表数据
    async getEmployeeList () {
      const res = await getEmployeeList(this.page)
      this.page.total = res.total
      this.list = res.rows
      // this.list = data
    },
    //页码值改变
    changePage (newPage) {
      this.page.page = newPage
      //获取列表
      this.getEmployeeList()
    },
    //处理聘用形式
    formatEmployment (row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id == cellValue)
      // console.log(obj)
      return obj ? obj.value : '未知'
    },
    //删除员工
    async deleteEmployee (id) {
      try {
        await this.$confirm('是否删除该员工?')
        await delEmployee(id)
        this.$message.success('删除成功')
        //重新拉去数据
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    exportData () {
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      import('@/vendor/Export2Excel').then(async excle => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)
        excle.export_json_to_excel({
          header: Object.keys(headers), //表头 必填
          data, //具体数据 必填
          filename: '员工工资表', //非必填
        })
      })
    },
    formatJson (headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] == 'timeOfEntry' || headers[key] == 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] == 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id == item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    //头像二维码
    showQrCode (url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该员工没有上传头像')
      }
    },
    //点击角色按钮
    async editRole (id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }


}
</script>
<style>
</style>
